#include "StdAfx.h"
#include "ExternalFrogOperations.h"
#include "FilerFrogShellExt.h"

void ExternalFrogOperations::ExternalDecryptFileDialog(const wstring& filePath)
{
	CComObject<CFilerFrogShellExt>* pFilerFrogShellExt = NULL;
	HRESULT hr = CComObject<CFilerFrogShellExt>::CreateInstance(&pFilerFrogShellExt);

	if (SUCCEEDED(hr))
	{	
		pFilerFrogShellExt->ExternalDecryptFileDialog(filePath);
	}
}

void ExternalFrogOperations::ExternalJoinFileDialog(const wstring& filePath)
{
	CComObject<CFilerFrogShellExt>* pFilerFrogShellExt = NULL;
	HRESULT hr = CComObject<CFilerFrogShellExt>::CreateInstance(&pFilerFrogShellExt);

	if (SUCCEEDED(hr))
	{	
		pFilerFrogShellExt->ExternalJoinFileDialog(filePath);
	}
}

bool ExternalFrogOperations::RedoLastDesktopSort()
{
	bool retVal = false;

	IShellWindows* psw = NULL;

	HRESULT coInitHr = CoInitialize(NULL);

	HRESULT hr = CoCreateInstance(CLSID_ShellWindows, NULL, CLSCTX_LOCAL_SERVER, IID_PPV_ARGS(&psw));

	if (SUCCEEDED(hr)) 
	{ 
		HWND hwnd; 
		IDispatch* pdisp; 
		VARIANT vEmpty = {}; // VT_EMPTY 

		if (S_OK == psw->FindWindowSW(&vEmpty, &vEmpty, SWC_DESKTOP, (long*)&hwnd, SWFO_NEEDDISPATCH, &pdisp)) 
		{	
			if (pdisp)
			{
				ExplorerController explorerController;
				explorerController.SetSitePtr(pdisp);
				retVal = explorerController.SortItemsByPathListWithLastConfig(true);
				pdisp->Release();
				pdisp = NULL;
			}
		}

		psw->Release();
		psw = NULL;
	}

	if (coInitHr == S_OK)
	{
		CoUninitialize();
	}

	return retVal;
}

static HHOOK g_Hook = NULL;

HINSTANCE GetHInstance()
{   
	return GetModuleHandle(NULL);

	MEMORY_BASIC_INFORMATION mbi;
	WCHAR szModule[MAX_PATH];

	SetLastError(ERROR_SUCCESS);
	if (VirtualQuery(GetHInstance,&mbi,sizeof(mbi)))
	{
		if (GetModuleFileName((HINSTANCE)mbi.AllocationBase,szModule,sizeof(szModule)))
		{
			return (HINSTANCE)mbi.AllocationBase;
		}        
	}
	return NULL;
}

void InstallHook()
{
	HINSTANCE hInstance = GetHInstance();
	g_Hook = SetWindowsHookEx(WH_GETMESSAGE, (HOOKPROC)MsgHookProc, hInstance, 0);
}


void RemoveHook()
{
	UnhookWindowsHookEx(g_Hook); 
}

LRESULT CALLBACK MsgHookProc(int code, WPARAM wParam, LPARAM lParam)
{
	// required checking
	if (g_Hook)
	{
		// call CallNextHookEx and return immediately if nCode < 0
		if ( code < 0 )
		{
			return CallNextHookEx(g_Hook, code, wParam, lParam);
		}
		
		MSG* pMsg = (MSG*) lParam;

	}

	return 0;
}